import { findAllGroupContainers, isElementVisible, getElementIdentifier } from './group-helper.js';
import { selectors } from './config.js';

// 标签页管理器
class TabManager {
  constructor() {
    this.tabGroups = [];
    this.currentGroupIndex = 0;
    this.currentTabIndex = 0;
    this.processedTabs = new Set();
    this.currentContainer = null; // 当前处理的容器
    this.groupContainers = []; // 存储已识别的分组容器
  }

  // 初始化标签页
  async initialize() {
    this.tabGroups = this.findTabGroups();
    // 初始化时获取所有分组容器
    const { containers } = findAllGroupContainers(document.body);
    this.groupContainers = containers;
    return this.tabGroups.length > 0;
  }

  // 查找所有标签组（支持tabBar和radioGroup两种类型）
  findTabGroups() {
    const groups = [];
    // 1. 传统tabBar类型
    const tabGroups = Array.from(document.querySelectorAll(selectors.tabBar))
      .filter(groupEl => isElementVisible(groupEl));
    
    console.log('找到标签组元素:', tabGroups.map((_, index) => `tab-group-${index}`));
    
    tabGroups.forEach((groupEl, index) => {
      const identifier = `tab-group-${index}`;
      groupEl.setAttribute('data-tracker-id', identifier);
      const items = Array.from(groupEl.querySelectorAll(selectors.tabItem))
        .filter(el => isElementVisible(el));
      const options = items
        .map(el => el.innerText.trim())
        .filter(Boolean);
      groups.push({
        groupIndex: groups.length,
        identifier,
        options,
        element: groupEl,
        type: 'tabBar'
      });
    });
    // 2. 新增：单选按钮组类型
    const radioGroups = Array.from(document.querySelectorAll(selectors.radioGroup))
      .filter(groupEl => isElementVisible(groupEl))
      .filter(groupEl => this.groupContainers.some(container => container.contains(groupEl)));
    radioGroups.forEach((groupEl, index) => {
      const identifier = `radio-group-${index}`;
      groupEl.setAttribute('data-tracker-id', identifier);
      const buttons = groupEl.querySelectorAll(selectors.radioButton);
      const options = Array.from(buttons)
        .map(btn => btn.textContent.trim())
        .filter(Boolean);
      groups.push({
        groupIndex: groups.length,
        identifier,
        options,
        element: groupEl,
        type: 'radioGroup'
      });
    });
    return groups;
  }

  // 获取元素的DOM路径
  getElementPath(element) {
    if (!(element instanceof Element)) return '';
  
    const path = [];
  
    while (element && element.nodeType === Node.ELEMENT_NODE) {
      let selector = element.nodeName.toLowerCase();
  
      if (element.id) {
        selector += `#${CSS.escape(element.id)}`;
        path.unshift(selector);
        break; // ID 已经唯一，可以中止向上查找
      } else {
        if (element.parentNode) {
          const siblings = Array.from(element.parentNode.children)
            .filter(e => e.nodeName === element.nodeName);
          if (siblings.length > 1) {
            const index = siblings.indexOf(element) + 1;
            selector += `:nth-of-type(${index})`;
          }
        }
  
        if (element.className) {
          const safeClass = element.className.trim().split(/\s+/).map(CSS.escape).join('.');
          if (safeClass) selector += `.${safeClass}`;
        }
  
        path.unshift(selector);
        element = element.parentElement;
      }
    }
  
    return path.join(' > ');
  }  

  // 获取当前标签信息
  getCurrentTab() {
    const group = this.tabGroups[this.currentGroupIndex];
    if (!group) return null;
    
    return {
      groupIndex: this.currentGroupIndex,
      tabIndex: this.currentTabIndex,
      name: group.options[this.currentTabIndex],
      element: this.getTabElement(this.currentGroupIndex, this.currentTabIndex)
    };
  }

  // 移动到下一个标签
  async moveToNextTab() {
    const group = this.tabGroups[this.currentGroupIndex];
    if (!group) return false;

    this.currentTabIndex++;
    
    // 如果当前组已处理完，移动到下一组
    if (this.currentTabIndex >= group.options.length) {
      this.currentGroupIndex++;
      this.currentTabIndex = 0;
      
      // 如果所有组都处理完，返回false
      if (this.currentGroupIndex >= this.tabGroups.length) {
        return false;
      }
    }

    return true;
  }

  // 处理当前标签
  async processCurrentTab(handler) {
    const tab = this.getCurrentTab();
    if (!tab) return null;

    const tabKey = `${tab.groupIndex}-${tab.tabIndex}`;
    if (this.processedTabs.has(tabKey)) {
      return null;
    }

    try {
      await this.scrollToTab(tab.groupIndex);
      await this.clickTab(tab.groupIndex, tab.tabIndex);
      
      // 重新读取标签组
      this.tabGroups = this.findTabGroups();
      console.log('点击后重新读取标签组:', this.tabGroups.map(g => getElementIdentifier(g.element)));
      
      // 重新读取分组容器（从当前标签组开始）
      const { containers } = findAllGroupContainers(document.body, null);
      this.groupContainers = containers;
      console.log('点击后重新读取分组容器:', this.groupContainers.map(c => getElementIdentifier(c)));
      
      const result = await handler(tab);
      this.processedTabs.add(tabKey);
      return result;
    } catch (error) {
      console.error(`处理标签失败: ${tab.name}`, error);
      return null;
    }
  }

  // 滚动到标签位置
  async scrollToTab(groupIndex) {
    const group = this.tabGroups[groupIndex];
    if (!group) return;

    const rect = group.element.getBoundingClientRect();
    const scrollY = window.scrollY + rect.top - 100;

    window.scrollTo({
      top: scrollY,
      behavior: 'smooth'
    });

    await new Promise(resolve => setTimeout(resolve, 500));
  }

  // 点击标签
  async clickTab(groupIndex, tabIndex) {
    const tabElement = this.getTabElement(groupIndex, tabIndex);
    if (!tabElement) return;

    console.log('点击标签:', 
      groupIndex,
      tabIndex,
      getElementIdentifier(tabElement)
    );

    tabElement.click();
    await new Promise(resolve => setTimeout(resolve, 1000));

    // 在标签切换后设置日期
    if (window._customDateRange && window.tpl?.module?.dateManager) {
      console.log('标签切换后设置日期:', window._customDateRange);
      await window.tpl.module.dateManager.setCustomDateRange(window._customDateRange.startDate, window._customDateRange.endDate);
    }
  }

  // 获取标签元素
  getTabElement(groupIndex, tabIndex) {
    const group = this.tabGroups[groupIndex];
    if (!group) return null;

    if (group.type === 'radioGroup') {
      const buttons = group.element.querySelectorAll(selectors.radioButton);
      return buttons[tabIndex] || null;
    } else {
      const items = group.element.querySelectorAll(selectors.tabItem);
      return items[tabIndex] || null;
    }
  }

  // 检查标签是否在指定容器内
  isTabInContainer(tabElement, container) {
    if (!tabElement || !container) return false;
    
    // 输出调试信息
    console.log('检查标签是否在容器内:', {
      tabElement: this.getElementPath(tabElement),
      container: this.getElementPath(container)
    });
    
    // 获取标签组所在的容器
    const tabContainer = this.findTabContainer(tabElement);
    if (!tabContainer) {
      console.log('找不到标签组容器');
      return false;
    }
    
    // 获取目标容器
    const targetContainer = this.findTargetContainer(container);
    if (!targetContainer) {
      console.log('找不到目标容器');
      return false;
    }
    
    // 检查标签组容器是否在目标容器内
    const isInContainer = this.isElementInContainer(tabContainer, targetContainer);
    console.log('标签组是否在容器内:', isInContainer);
    return isInContainer;
  }

  // 查找标签所在的容器
  findTabContainer(element) {
    // 向上查找最近的标签栏容器
    let current = element;
    while (current && current !== document.documentElement) {
      if (current.classList.contains(selectors.tabBarItem.replace('.', ''))) {
        return current;
      }
      current = current.parentElement;
    }
    return null;
  }

  // 查找目标容器
  findTargetContainer(element) {
    // 从已识别的分组容器中查找
    return this.groupContainers.find(container => 
      this.isElementInContainer(element, container)
    ) || null;
  }

  // 检查元素是否在容器内
  isElementInContainer(element, container) {
    if (!element || !container) return false;

    console.log('检查元素是否在容器内:', {
      element_id: getElementIdentifier(element),
      container_id: getElementIdentifier(container)
    });

    // 使用DOM的contains方法判断元素是否在容器内
    const isInContainer = container.contains(element);
    
    console.log('元素是否在容器内:', isInContainer, {
      element_path: this.getElementPath(element),
      container_path: this.getElementPath(container)
    });
    
    return isInContainer;
  }

  // 设置当前处理的容器
  setCurrentContainer(container) {
    this.currentContainer = container;
  }

  // 获取容器内的标签组
  getContainerTabGroups(specificContainer = null) {
    console.log('【getContainerTabGroups】specificContainer:', 
      specificContainer ? getElementIdentifier(specificContainer) : null);
      
    if (this.groupContainers.length === 0) {
      console.log('没有找到任何分组容器，返回空');
      return [];
    }
    
    console.log('【getContainerTabGroups】tabGroups:', 
      this.tabGroups.map(g => getElementIdentifier(g.element)));
    
    const innerGroups = this.tabGroups.filter(group => {
      if (specificContainer) {
        // 如果指定了特定容器，只检查是否在该容器内
        return this.isElementInContainer(group.element, specificContainer);
      } else {
        // 原有逻辑：检查是否在任何分组容器内
        return this.groupContainers.some(container => 
          this.isElementInContainer(group.element, container)
        );
      }
    });
    
    console.log('找到组内标签组:', innerGroups.map(g => ({
      identifier: getElementIdentifier(g.element),
      options: g.options
    })));
    
    return innerGroups;
  }

  // 获取容器外的标签组
  getOuterTabGroups() {
    if (this.groupContainers.length === 0) {
      console.log('没有找到任何分组容器，返回所有标签组');
      return this.tabGroups;
    }

    console.log('groupContainers:', 
      this.groupContainers.map(c => getElementIdentifier(c)));
    
    const outerGroups = this.tabGroups.filter(group => {
      // 检查标签组是否不在任何分组容器内
      return !this.groupContainers.some(container => 
        this.isElementInContainer(group.element, container)
      );
    });
    
    console.log('找到组外标签组:', outerGroups.map(g => ({
      identifier: getElementIdentifier(g.element),
      options: g.options
    })));
    
    return outerGroups;
  }

  // 重置状态
  reset() {
    this.currentGroupIndex = 0;
    this.currentTabIndex = 0;
    this.processedTabs.clear();
    this.currentContainer = null;
  }
}

export default TabManager; 